package com.gaojun.tool;

import java.io.File;

import org.bytedeco.javacpp.avcodec;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.FFmpegFrameRecorder;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.FrameGrabber.Exception;

/**
 * 转换视频
 * @author gj
 *
 */
public class ConvertVideo {

	public void convert(File file, String changeType, String fileName) {
		FFmpegFrameGrabber frameGrabber = new FFmpegFrameGrabber(file.getAbsolutePath());
		Frame captured_frame = null;
		FFmpegFrameRecorder recorder = null;
		try {
			frameGrabber.start();

			recorder = new FFmpegFrameRecorder(fileName, frameGrabber.getImageWidth(), frameGrabber.getImageHeight(),
					frameGrabber.getAudioChannels());
			switch (changeType) {
			case ".mp4":
				recorder.setVideoCodec(avcodec.AV_CODEC_ID_MPEG4); // avcodec.AV_CODEC_ID_H264  //AV_CODEC_ID_MPEG4
				recorder.setFormat("mp4");
				break;
			case ".avi":
				recorder.setVideoCodec(avcodec.AV_CODEC_ID_MPEG4); // avcodec.AV_CODEC_ID_H264  //AV_CODEC_ID_MPEG4
				recorder.setFormat("avi");
				break;
			case ".flv":
				recorder.setVideoCodec(avcodec.AV_CODEC_ID_FLV1); // avcodec.AV_CODEC_ID_H264  //AV_CODEC_ID_MPEG4
				recorder.setFormat("flv");
				break;
			case ".mov":
				recorder.setVideoCodec(avcodec.AV_CODEC_ID_FLV1); // avcodec.AV_CODEC_ID_H264  //AV_CODEC_ID_MPEG4
				recorder.setFormat("mov");
				break;

			default:
				break;
			}

			recorder.setFrameRate(frameGrabber.getFrameRate());
			recorder.setSampleFormat(frameGrabber.getSampleFormat());//
			recorder.setSampleRate(frameGrabber.getSampleRate());
			recorder.start();

			while (true) {
				try {
					captured_frame = frameGrabber.grabFrame();
					recorder.setTimestamp(frameGrabber.getTimestamp());
					recorder.record(captured_frame);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (captured_frame == null) {
					System.out.println("!!! Failed cvQueryFrame");
					break;
				}

			}
			recorder.stop();
			recorder.release();
			frameGrabber.stop();
		} catch (org.bytedeco.javacv.FrameRecorder.Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
